/* eslint react/prefer-stateless-function:0, react/prop-types:0 */

import React, { Component } from 'react';
import style from './style.css';
import play from '../../images/play.jpg';

export default class extends Component {

  static propTypes = {};

  static defaultProps = {
    id: 1,
  };

  constructor(props) {
    super(props);
  }

  state = {
    playText: '播放',
    currentTime: '00:00',
    duration: '00:00',
  };

  getFormatTime(time = 0) {
    let m = parseInt(time % 3600 / 60);
    let s = parseInt(time % 60);
    m = m < 10 ? "0" + m : m;
    s = s < 10 ? "0" + s : s;
    return m + ":" + s;
  }

  play() {
    const video = document.getElementById(`video-${this.props.id}`);
    if (video.paused) {
      this.setState({
        playText: '暂停',
      });
      video.play();
    } else {
      this.setState({
        playText: '播放',
      });
      video.pause();
    }
  }

  fullscreen() {
    const video = document.getElementById(`video-${this.props.id}`);
    video.webkitRequestFullScreen();
  }

  render() {
    const { id, src } = this.props;
    const { playText, currentTime, duration } = this.state;
    return (
      <div className={style.video_panel}>
        <video className="video" preload="auto"  webkit-playsinline="true" playsinline="true"  x-webkit-airplay="allow" x5-video-player-type="h5" x5-video-player-fullscreen="true" onClick={::this.play} id={`video-${id}`} poster={play}>
          <source src={src} />
          对不起，您的设备不支持播放视频。
        </video>
        <div className={style.controls}>
          <a className={style.play} onClick={::this.play}>{playText}</a>
          <div className={style.time}>{currentTime}/{duration}</div>
          <a className={style.fullscreen} onClick={::this.fullscreen}>全屏</a>
        </div>
      </div>
    );
  }

  componentDidMount() {
    const video = document.getElementById(`video-${this.props.id}`);

    video.addEventListener('canplay', () => {
      this.setState({
        duration: this.getFormatTime(video.duration)
      });
    }, false);

    video.addEventListener('canplaythrough', () => {
      this.setState({
        duration: this.getFormatTime(video.duration)
      });
    }, false);

    video.addEventListener('timeupdate', () => {
      this.setState({
        currentTime: this.getFormatTime(video.currentTime)
      });
    }, false);

    video.addEventListener('ended', () => {
      this.setState({
        playText: '播放',
      });
    }, false);
  }
}